
#include <cstdint>
#include <cstdlib>
#include <string>
#include "connection.h"
#include "loop_event.hpp"
#include "server.h"
#include <iostream>
#include "client.h"
#include <thread>
#include <unistd.h>


void OnMessageCallback(Client * client, const std::string & message)
{
    std::cout << "client channel id : " << client->ChannelId() << "  recve message : " << message << std::endl;
}

void ClientThread(LoopEvent & loop)
{
    sleep(2);
    std::vector<Client*> client_vec;
    for (int index = 0; index < 10; index++)
    {
        client_vec.push_back(new Client(&loop));
        client_vec[index]->Connect("127.0.0.1", 10024);
        client_vec[index]->SetOnMessage(OnMessageCallback);
    }
    for (int index = 0; index < 10 && client_vec.size() > 0; index++)
    {
        std::string content = std::to_string(time(nullptr));
        for (auto & data : client_vec)
        {
            data->SendMessage(content);
        }
        usleep(1000 * 1000);
    }
    for (auto & data : client_vec)
    {
        data->CloseConnection();
    }
}

int main(int argc, char * argv[])
{

    std::cout << "begin" << std::endl;
    LoopEvent loop;

    Server server(&loop);

    server.SetOnMessageFunc([&](Connection * connect, const uint8_t * data, int length){

        connect->m_data_buffer->WriteData(data, length);
        connect->m_data_buffer->RemoveData(length);
    });
    server.Listen(10024);

    std::thread thd(ClientThread, std::ref(loop));

    loop.Run();

    thd.join();

    return EXIT_SUCCESS;
}